/*-----------------------------------------------------------------------------------
Name: Sangyoon Park
Date: January 25 2023
This do file does : 
	Create figures for Online Appendix
-----------------------------------------------------------------------------------*/
clear all
set matsize 10000
set maxvar 10000
set more off
capture log close


#delim ;

/*-----------------------------------------------------------------------------------
			 Set up
-----------------------------------------------------------------------------------*/
*** Setting up files;
	glo datafile "qu_analysis"; 	// type in the name of the datafile that you want to create;

*** Set up program;
 ** Number Format;
	capture program drop autoformat;
	program define autoformat;

	if int(`1')==`1' global format "%12.0f";
	else if abs(`1')>10 global format "%9.1f";
	else if abs(`1')>1 global format "%9.2f";
	else if abs(`1')>.1 global format "%9.3f";
	else if abs(`1')>.01 global format "%9.3f";
	else if abs(`1')>.001 global format "%9.3f";
	else if abs(`1')>.0001 global format "%9.4f";
	else if abs(`1')<.00001 global format "%9.5f";

	end;
	
	
/*-----------------------------------------------------------------------------------
			 		DATA = GAME
-----------------------------------------------------------------------------------*/		

	import excel "${raw_path}/DATA_GAME_ALL.xlsx", sheet("Sheet1") firstrow ;
	tempfile game;
	save `game';
	clear;		
	
/*-----------------------------------------------------------------------------------
			 		DATA = EXPORTER SURVEY
-----------------------------------------------------------------------------------*/		

	use "${data_path}/INTERMEDIARY_LONG.dta", clear;
	rename age firmage;
		egen group_id = group(strata st_tgroup);
		gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
		gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
		gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
		gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
		gen tr_fXcert = tr_farm * certelig;
		gen tr_iXcert = tr_int * certelig;
		gen tr_jXcert = tr_joint * certelig;	
	tempfile intdata;
	save `intdata';
	clear;	
	
/*-----------------------------------------------------------------------------------
			 		DATA = FARMER SURVEY
-----------------------------------------------------------------------------------*/			
		
	
*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen control = (st_tgroup == 1 | st_tgroup == 5);
	

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;


	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var tr_farm "Farmer Training";
	lab var tr_int "Exporter Training";
	lab var tr_joint "Joint Training";
	lab var certelig "Certificate Eligibility (C.E.)";
	lab var tr_fXcert "C.E. $\times$ Farmer Training";
	lab var tr_iXcert "C.E. $\times$ Exporter Training";
	lab var tr_jXcert "C.E $\times$ Joint Training";
	lab var std_knowledge "Farmer GAP Knowledge";
	lab var std_perception "Farmer Food Safety Awareness";
	lab var int_std_knowledge "Exporter GAP Knowledge";
	lab var dist_nearest_treated "Distance to nearest jointly trained farmer (km)";
	lab var farmer_in2 "Number of farmers within 2km distance";
	lab var trader_in3 "Number of exporters within 3km distance";
	lab var trader_in2 "Number of exporters within 2km distance";
	lab var dist_jointtrader "Distance to nearest jointly trained exporter (km)";

	
tempfile maindata;
save `maindata';
clear;	


/*-----------------------------------------------------------------------------------
			 	 PRICE PREMIUM on GAP Compliance by Treatment Group (Online Appendix Figure A-4)
-----------------------------------------------------------------------------------*/	


use `maindata';


local balance2 age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base totalvolume_base;

lab var vietgap "Received VietGAP certificate before";
lab var std_score "Standardized GAP audit score";
lab var std_meanquality "Product attribute index (mean of z-score)";

gen vietgap_2yr = inlist(vietgap_year, 2017, 2018);
lab var vietgap_2yr "Have VietGAP certificate at baseline";


** Setting;	
	
xi i.st_tgroup*std_score, prefix(G) noomit;
lab var Gst_Xstd_s_1 "No training $\times$ Standardized GAP audit score";
lab var Gst_Xstd_s_2 "Farmer training $\times$ Standardized GAP audit score";
lab var Gst_Xstd_s_3 "Exporter training $\times$ Standardized GAP audit score";
lab var Gst_Xstd_s_4 "Joint training $\times$ Standardized GAP audit score";
lab var Gst_Xstd_s_5 "C.E. $\times$ Standardized GAP audit score";
lab var Gst_Xstd_s_6 "C.E. $\times$ Farmer training $\times$ Standardized GAP audit score";
lab var Gst_Xstd_s_7 "C.E. $\times$ Exporter training $\times$ Standardized GAP audit score";
lab var Gst_Xstd_s_8 "C.E. $\times$ Joint training $\times$ Standardized GAP audit score";

lab var Gst_Xstd_s_1 "No training";
lab var Gst_Xstd_s_2 "Farmer training";
lab var Gst_Xstd_s_3 "Exporter training";
lab var Gst_Xstd_s_4 "Joint training";
lab var Gst_Xstd_s_5 "Certificate Eligible";
lab var Gst_Xstd_s_6 "C.E. x Farmer training";
lab var Gst_Xstd_s_7 "C.E. x Exporter training";
lab var Gst_Xstd_s_8 "C.E. x Joint training";


xi i.st_tgroup*std_meanquality, prefix(P) noomit;
lab var Pst_Xstd_m_1 "No training $\times$ Product attribute index";
lab var Pst_Xstd_m_2 "Farmer training $\times$ Product attribute index";
lab var Pst_Xstd_m_3 "Exporter training $\times$ Product attribute index";
lab var Pst_Xstd_m_4 "Joint training $\times$ Product attribute index";
lab var Pst_Xstd_m_5 "C.E. $\times$ Product attribute index";
lab var Pst_Xstd_m_6 "C.E. $\times$ Farmer training $\times$ Product attribute index";
lab var Pst_Xstd_m_7 "C.E. $\times$ Exporter training $\times$ Product attribute index";
lab var Pst_Xstd_m_8 "C.E. $\times$ Joint training $\times$ Product attribute index";



preserve;

** Estimation;
	local outcome "price";
	local vietgap "vietgap_2yr";

		foreach y of local outcome {;
		eststo: qui reg log_price i.st_tgroup vietgap_2yr Gst_Xstd_s_* Pst_X* `balance2' `intbalance' i.strata i.round, robust cluster(group_id);

		
		};

		esttab, keep (Gst_Xstd_*) cells(b ci_l ci_u) nocons;
		mat B1 = r(coefs);
		mat C1 = B1';

		est clear;
restore;		
		
drop Gst_Xstd_s_*;
forvalues i = 1(1)8 {;		
	gen Gst_Xstd_s_`i' = Pst_Xstd_m_`i';
	};

drop Pst_Xstd_m*;
xi i.st_tgroup*std_score, prefix(P) noomit;
	

lab var Gst_Xstd_s_1 "No training";
lab var Gst_Xstd_s_2 "Farmer training";
lab var Gst_Xstd_s_3 "Exporter training";
lab var Gst_Xstd_s_4 "Joint training";
lab var Gst_Xstd_s_5 "Certificate Eligible";
lab var Gst_Xstd_s_6 "C.E. x Farmer training";
lab var Gst_Xstd_s_7 "C.E. x Exporter training";
lab var Gst_Xstd_s_8 "C.E. x Joint training";

		foreach y of local outcome {;
		eststo: qui reg log_price i.st_tgroup vietgap_2yr Gst_Xstd_s_* Pst_X* `balance2' `intbalance' i.strata i.round, robust cluster(group_id);

	
		};		
		
		esttab, keep (Gst_Xstd_*) cells(b ci_l ci_u) nocons;
		mat B2 = r(coefs);
		mat C2 = B2';		

grstyle init;
grstyle color background white;		
		
coefplot matrix(C1), label(GAP score premium) offset(0.1) ci((2 3)) ciopts(recast(rcap) lcol(black)) lc(black) mc(black) xline(0,lc(black) lp(dash)) plotregion(style(none)) xtitle("GAP score premium") graphregion(color(white)) bgcolor(white) xlabel(,labsize(medium));

	graph export "${figure_path}/pricepremium_bytreatment_v2.png", replace;

est clear;
clear;


	
/*-----------------------------------------------------------------------------------
			 		FIGURE - HEATPLOT FOR CONTRACT TRADE (Online Appendix Figure A-5)
-----------------------------------------------------------------------------------*/	

clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;

	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var age "Age";
	lab var female "Female";
	lab var edu_second "Secondary Education";
	lab var exp_dragon "Experience growing dragon fruit (years)";
	lab var ha_whitedragon "Size of dragon fruit farm (hectares)";
	lab var tree_whitedragon "Number of dragon fruit trees";
	lab var anycert_base "Received any agricultural certificate before";
	lab var loan_any_base "Ever received loan for farm investment";
	lab var save_bank_base "Ever saved at bank";
	lab var mean_trust_base "Mean score on trust measurement";
	lab var mean_business_base "Mean score on business measurement";
	lab var mean_confidence_base "Mean score on confidence measurement";
	lab var raven_total "Raven matrices score";
	lab var present_bias_base "Time discounting - present biased";
	lab var gap_comply_base "Self-reported GAP compliance";
	lab var dum_market1 "China";
	lab var dum_market2 "Asia (excluding China)";
	lab var dum_market3 "EU/US";
	lab var dum_market4 "Domestic";
	lab var std_score "GAP compliance";
	lab var std_sweet "Sweetness";
	lab var std_skin "Skin";
	lab var std_bract "Bract";
	lab var std_length "Length";
	lab var std_width "Width";
	lab var std_weight "Weight";
	lab var tr_farm "Farmer Training";
	lab var tr_int "Intermediary Training";
	lab var tr_joint "Joint Training";
	lab var certelig "Certificate Eligibility";
	lab var tr_fXcert " $\times$ Farmer Training";
	lab var tr_iXcert " $\times$ Intermediary Training";
	lab var tr_jXcert " $\times$ Joint Training";
	lab var sum_overmrl_eu "Residue $\geq$ E.U. Limit";
	lab var progmeet "Buyer was program participant";


** Estimation;
	gen quality = .;
	gen qualityXjoint = .;
	gen qualityXint = .;
	gen qualityXfarm = .;
	gen qualityXprogmeet = .;
	gen qualityXcontract = .;
	gen qualityXjointXprogmeet = .;
	gen qualityXjointXnoprog = .;
	gen qualityXprogmeetXcontract = .;	
	gen qualityXjointXcontract = .;
	gen qualityXjointXnocontract = .;
	replace buyer_contract = 2 if buyer_contract == 1;
	replace buyer_contract = 0 if dum_type3 == 0;
	replace buyer_contract = 0 if buyer_contract == 3;	
	gen jointXprogmeet = tr_joint*progmeet;
	gen jointXnoprog = tr_joint*(1-progmeet);
	gen jointXcontract = tr_joint*(buyer_contract == 2);
	gen jointXnocontract = tr_joint*(buyer_contract == 0);
	gen havecontract = (buyer_contract ==2);
	gen progmeetXcontract = progmeet*havecontract;
	lab var quality "Product Quality";
	lab var progmeet "Trade within Cluster";
	lab var qualityXcontract "Product Quality $\times$ Contract";
	lab var qualityXjoint "Product Quality $\times$ Joint Training";
	lab var qualityXint "Product Quality $\times$ Intermediary Training";	
	lab var qualityXfarm "Product Quality $\times$ Farmer Training";		
	lab var qualityXjointXprogmeet "Product Quality $\times$ Joint Training $\times$ Trade within Cluster";	
	lab var qualityXjointXnoprog "Product Quality $\times$ Joint Training $\times$ Trade outside Cluster";
	lab var qualityXjointXcontract "Product Quality $\times$ Joint Training $\times$ Contract";	
	lab var qualityXjointXnocontract "Product Quality $\times$ Joint Training $\times$ No Contract";
	lab var qualityXprogmeet "Product Quality $\times$ Trade within Cluster";
	lab var qualityXprogmeetXcontract "Product Quality $\times$ Trade within Cluster $\times$ Contract";		
	lab var jointXprogmeet "Joint Training $\times$ Trade within Cluster";
	lab var jointXnoprog "Joint Training $\times$ Trade outside Cluster";
	lab var jointXcontract "Joint Training $\times$ Contract";
	lab var jointXnocontract "Joint Training $\times$ No Contract";	
	lab var havecontract "Contract";	
	lab var progmeetXcontract "Trade within Cluster $\times$ Contract";	

	lab var buyer_price "Farm-gate price (VND)";
	lab var std_score "Standardized GAP Compliance Score";
	lab var mean_std_pest_eu "Mean Pesticide Residue (Unit: MRL)";
	lab var std_meanquality "Observable Product Quality Index";	
	
	heatplot havecontract std_score buyer_price, hexagon ramp(right space(15) length(60) subtitle("Contract")) cuts(0 (0.1) 1) graphregion(fcolor("white")) ylab(, nogrid) saving(score, replace);
	graph export "${figure_path}/heatmap_std_score.png", replace;
	
	heatplot havecontract mean_std_pest_eu buyer_price, hexagon ramp(right space(15) length(60) subtitle("Contract")) cuts(0 (0.1) 1) graphregion(fcolor("white")) ylab(, nogrid) saving(pesticide, replace);
	graph export "${figure_path}/heatmap_meanpesticide.png", replace;
	heatplot havecontract std_meanquality buyer_price, hexagon ramp(right space(15) length(60) subtitle("Contract")) cuts(0 (0.1) 1) graphregion(fcolor("white")) ylab(, nogrid) saving(observable, replace);
	graph export "${figure_path}/heatmap_meanquality.png", replace;
	
gr combine score.gph pesticide.gph observable.gph, col(2) graphregion(fcolor("white"));
	graph export "${figure_path}/heatmap_all.png", replace;		
	
	
	
	







/*-----------------------------------------------------------------------------------
			 Figure - Price Premium for Quality by Export Market (Online Appendix Figure A-6)
-----------------------------------------------------------------------------------*/	
#delim cr
*** Read data
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace

	rename followup round
	drop if round == 0
	
	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP"
	keep if _merge == 3
	
*** Drop control communes

	drop if control_commune == 1
	
*** Generate dummy for treatment groups
	
	tab st_tgroup, gen(dum_tgroup)
	
*** Cluster for standard errors

	egen group_id = group(strata st_tgroup)

*** Generate treatment levels and interaction terms

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6)
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7)
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8)
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8)
	gen tr_fXcert = tr_farm * certelig
	gen tr_iXcert = tr_int * certelig
	gen tr_jXcert = tr_joint * certelig 


** Generate outcome variables

	gen log_buyer_price = log(buyer_price)
	gen vietgap_2yr = inlist(vietgap_year, 2017, 2018)		
		
*** Define local variables
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert



	local balance age female edu_second exp_dragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base revenue_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base
	
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base totalvolume_base 


	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3	
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var tr_farm "Farmer Training"
	lab var tr_int "Intermediary Training"
	lab var tr_joint "Joint Training"
	lab var certelig "Certificate Eligibility"
	lab var tr_fXcert " $\times$ Farmer Training"
	lab var tr_iXcert " $\times$ Intermediary Training"
	lab var tr_jXcert " $\times$ Joint Training"
	

/*-----------------------------------------------------------------------------------
			 		Figure: Price Premium
-----------------------------------------------------------------------------------*/
** Set figure style
** install packages if not ready
	*ssc install grstyle
	*ssc install palettes
	*ssc install colrspace
	*findit grc1leg
	
grstyle init
grstyle color background white


	
	reg log_buyer_price std_score std_meanquality vietgap_2yr `treat_coef' `balance' `intbalance' i.strata i.round if dum_market1 == 1 | dum_market4 == 1, robust cluster(group_id)
	
	nlcom (certificate: _b[vietgap_2yr]) (audit: _b[std_score]) (observable: _b[std_meanquality]) , post

	eststo gappremium_china
	
	reg log_buyer_price std_score std_meanquality vietgap_2yr `treat_coef' `balance' `intbalance' i.strata i.round if dum_market2 == 1 | dum_market3 == 1, robust cluster(group_id)
	
	nlcom (certificate: _b[vietgap_2yr]) (audit: _b[std_score]) (observable: _b[std_meanquality]) , post

	eststo gappremium_asia

	reg log_buyer_price std_score std_meanquality vietgap_2yr `treat_coef' `balance' `intbalance' i.strata i.round if dum_market3 == 1, robust cluster(group_id)
	
	nlcom (certificate: _b[vietgap_2yr]) (audit: _b[std_score]) (observable: _b[std_meanquality]) , post

	eststo gappremium_eu
	
	
	coefplot (gappremium_china, label(China and Domestic markets) offset(0.1)) (gappremium_asia, label(Other Asian and EU/US markets) offset(-0.1)), coeflabels(certificate = "VietGAP Certificate" audit = "GAP Audit Score" observable = "Observable Attribute Index", notick labsize(medlarge)) xlabel(, labsize(medlarge)) ylabel(, nogrid) legend(rows(2) size(medlarge)) ciopts(recast(rspike)) xline(0, lcolor(black) lwidth(thin)) subtitle(, fcolor(white) bcolor(white) size(medlarge)) saving(pricepremium, replace)
	graph export "${figure_path}/pricepremium.png", replace












